<?php

namespace App\Logic\User;

use App\Logic\Logic;
use App\Model\User\UserBean;
use App\Model\User\UserModel;
use App\Msg\MsgCode;
use EasySwoole\Core\Utility\Random;

class UserLogic extends Logic {
	public function register(UserBean $user): string {
		$userM = new UserModel ();
		
		if (! empty ( $user->getEmail() )) {
			$checkUser = $userM->getUserByEmail( $user->getEmail() );
			if (! empty ( $checkUser->getUid () )) {
				$this->setMsg ( MsgCode::USER_EXIST );
			}
		}
		return $userM->addUser ( $user );
	}
	function Login($accout, $password): string {
		$password = trim ( $password );
		$accout = trim ( $accout );
		$userM = new UserModel ();
		
		if (! empty ( $accout )) {
			$LoginUser = $userM->getUserByEmail ( $accout );
			if (empty ( $LoginUser->getUid () )) {
				$this->setMsg ( MsgCode::USER_NOT_EXIST );
			} else {
				if (empty ( $password )) {
					$this->setMsg ( MsgCode::PASSWORD_IS_NULL );
				}
				if ($LoginUser->getPassword () != md5 ( $password )) {
					$this->setMsg ( MsgCode::USER_PASSWORD_ERROR );
				} else {
					$token = $this->CreatLoginToken ( $LoginUser );
					(new UserModel ())->addUserToCache ( $token, $LoginUser );
					return $token;
				}
			}
		} else {
			$this->setMsg ( MsgCode::ACCOUNT_IS_NULL );
		}
	}
	function CreatLoginToken(UserBean $user) {
		return $token = md5 ( $user->getUid () . time () ) . Random::randNumStr ( 5 );
	}
	function checkIsLogin($token) {
		$user = (new UserModel ())->getUserByToken ( $token );
		if ($user->getUid ()) {
			return true;
		} else {
			return false;
		}
	}
}